<?
require_once(dirname(__FILE__) . '/../../classes/report_interface.inc.php');

abstract class LoggerModuleSourcesLinksReportBaseClass 
{
    protected $database;

    public function __construct(LoggerDatabase $database) 
    {
        $this->database = $database;
    }

    protected function GetLinksData($date1, $date2, $server, $start, $count)
    {
        $date1 = '\'' . mysql_escape_string($date1) . '\'';
        $date2 = '\'' . mysql_escape_string($date2) . '\'';

        $serverWhere = '';
        if ($server !== false)
        {
            $serverWhere = '`l`.`serv`=' . intval($server) . ' AND ';
        }

        $SelectSQL = 'SELECT `scheme`, `serv`, `s`.`string` AS `servStr`, `path`, `p`.`string` AS `pathStr`, `query`, `q`.`string` AS `queryStr`, SUM(`summ`) AS `summ` FROM (';
        $SelectSQL .= 'SELECT `l`.`scheme`, `l`.`serv`, `l`.`path`, `l`.`query`, SUM(`l`.`count`) AS `summ` ';
        $SelectSQL .= 'FROM `[PREF]module_sources_links_archive` `l` ';
        $SelectSQL .= 'WHERE '.$serverWhere.'`l`.`date`>='.$date1.' AND `l`.`date`<='.$date2.' ';
        $SelectSQL .= 'GROUP BY `l`.`scheme`, `l`.`serv`, `l`.`path`, `l`.`query` ';

        $SelectSQL .= 'UNION ALL ';

        $SelectSQL .= 'SELECT `l`.`scheme`, `l`.`serv`, `l`.`path`, `l`.`query`, COUNT(*) AS `summ` ';
        $SelectSQL .= 'FROM `[PREF]module_sources_links` `l` ';
        $SelectSQL .= 'WHERE '.$serverWhere.'`l`.`date`>='.$date1.' AND `l`.`date`<='.$date2.' ';
        $SelectSQL .= 'GROUP BY `l`.`scheme`, `l`.`serv`, `l`.`path`, `l`.`query` ';

        $SelectSQL .= ') AS `__temp_query` ';
        $SelectSQL .= 'LEFT JOIN `[PREF]module_sources_strings` `s` ON `s`.`id`=`__temp_query`.`serv` ';
        $SelectSQL .= 'LEFT JOIN `[PREF]module_sources_strings` `p` ON `p`.`id`=`__temp_query`.`path` ';
        $SelectSQL .= 'LEFT JOIN `[PREF]module_sources_strings` `q` ON `q`.`id`=`__temp_query`.`query` ';
        $SelectSQL .= 'GROUP BY `__temp_query`.`scheme`, `__temp_query`.`serv`, `__temp_query`.`path`, `__temp_query`.`query` ';
        $SelectSQL .= 'ORDER BY `summ` DESC, `scheme`, `serv`, `path`, `query` ';
        $SelectSQL .= 'LIMIT '.$start.','.$count;

        $data = array();
        $result = $this->database->Query($SelectSQL);
        if (!$result)
             trigger_error('Database Error: ' . $this->database->Error(), E_USER_ERROR);
        while ($row = $this->database->FetchAssoc($result))
        {
            $data[] = $row;
        }
        $this->database->FreeResult($result);
        return $data;
    }

    protected function GetServersData($date1, $date2, $start, $count)
    {
        $date1 = '\'' . mysql_escape_string($date1) . '\'';
        $date2 = '\'' . mysql_escape_string($date2) . '\'';

        $SelectSQL = 'SELECT `__temp_query`.`serv` AS `serv`, `s`.`string` AS `servStr`, SUM(`__temp_query`.`summ`) AS `summ` FROM (';

        $SelectSQL .= 'SELECT `l`.`serv`, SUM(`l`.`count`) AS `summ` ';
        $SelectSQL .= 'FROM `[PREF]module_sources_links_archive` `l` ';
        $SelectSQL .= 'WHERE `l`.`date`>='.$date1.' AND `l`.`date`<='.$date2.' ';
        $SelectSQL .= 'GROUP BY `l`.`serv` ';
        
        $SelectSQL .= 'UNION ALL ';

        $SelectSQL .= 'SELECT `l`.`serv`, COUNT(*) AS `summ` ';
        $SelectSQL .= 'FROM `[PREF]module_sources_links` `l` ';
        $SelectSQL .= 'WHERE `l`.`date`>='.$date1.' AND `l`.`date`<='.$date2.' ';
        $SelectSQL .= 'GROUP BY `l`.`serv` ';
    
        $SelectSQL .= ') AS `__temp_query` ';
        $SelectSQL .= 'LEFT JOIN `[PREF]module_sources_strings` `s` ON `s`.`id`=`__temp_query`.`serv` ';
        $SelectSQL .= 'GROUP BY `__temp_query`.`serv` ';
        $SelectSQL .= 'ORDER BY `summ` DESC, `servStr` ';
        $SelectSQL .= 'LIMIT '.$start.','.$count;

        $data = array();
        $result = $this->database->Query($SelectSQL);
        if (!$result)
             trigger_error('Database Error: ' . $this->database->Error(), E_USER_ERROR);
        while ($row = $this->database->FetchAssoc($result))
        {
            $data[] = $row;
        }
        $this->database->FreeResult($result);
        return $data;
    }
}

class LoggerModuleSourcesServersReport extends LoggerModuleSourcesLinksReportBaseClass implements LoggerReportInterface
{
    public function __construct(LoggerDatabase $database) 
    {
        parent::__construct($database);
    }

    public function GetReport($root, $date1, $date2, $params = false)
    {
        $limit_start = 0;
        $limit_count = 100;

        $xml = $root->ownerDocument;

        $name = $xml->createElement('report_name', 'Переходы с серверов');
        $root->appendChild($name);

        $data = $this->GetServersData($date1, $date2, $limit_start, $limit_count);
        $reportData = $xml->createElement('report_data');
        $root->appendChild($reportData);

        foreach($data as $row)
        {
            $dataRow = $xml->createElement('row');
            $reportData->appendChild($dataRow);
            $dataRow->setAttribute('serverStr', $row['servStr']);
            $dataRow->setAttribute('serverId', $row['serv']);
            $dataRow->setAttribute('summ', $row['summ']);
        }

        if (count($data) == $limit_count)
        {
            $dataMore = $xml->createElement('report_data_more');
            $dataMore->setAttribute('start', $limit_count);
            $dataMore->setAttribute('count', $limit_count);
            $root->appendChild($dataMore);
        }

        $xsl = dirname(__FILE__) . '/templates/servers.xsl';
        $pi = $xml->createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="'.$xsl.'"');
        $xml->insertBefore($pi, $root);
        return true;
    }
}


class LoggerModuleSourcesServersMoreReport extends LoggerModuleSourcesLinksReportBaseClass implements LoggerReportInterface
{
    public function __construct(LoggerDatabase $database) 
    {
        parent::__construct($database);
    }

    public function GetReport($root, $date1, $date2, $params = false)
    {
        if (!is_array($params) || !isset($params['start']))
            return false;

        $limit_start = intval($params['start']);
        $limit_count = 100;

        if (isset($params['count']))
            $limit_count = intval($params['count']);

        $xml = $root->ownerDocument;

        $data = $this->GetServersData($date1, $date2, $limit_start, $limit_count);
        $reportData = $xml->createElement('report_data');
        $root->appendChild($reportData);

        foreach($data as $row)
        {
            $dataRow = $xml->createElement('row');
            $reportData->appendChild($dataRow);
            $dataRow->setAttribute('serverStr', $row['servStr']);
            $dataRow->setAttribute('serverId', $row['serv']);
            $dataRow->setAttribute('summ', $row['summ']);
        }

        $xsl = dirname(__FILE__) . '/templates/servers_more.xsl';
        $pi = $xml->createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="'.$xsl.'"');
        $xml->insertBefore($pi, $root);
        return true;
    }
}


class LoggerModuleSourcesLinksReport extends LoggerModuleSourcesLinksReportBaseClass implements LoggerReportInterface
{
    public function __construct(LoggerDatabase $database) 
    {
        parent::__construct($database);
    }

    public function GetReport($root, $date1, $date2, $params = false)
    {
        $limit_start = 0;
        $limit_count = 100;
        
        $server = false;
        $serverName = '';
        if (is_array($params) && isset($params['server']) && $params['server'])
        {
            $server = intval($params['server']);
            $SelectSQL = 'SELECT `string` FROM `[PREF]module_sources_strings` WHERE `id`='.$server;
            $result = $this->database->Query($SelectSQL);
            if ($result && $row = $this->database->FetchAssoc($result))
                $serverName = $row['string'];
            $this->database->FreeResult($result);
        }

        $xml = $root->ownerDocument;

        $name = $xml->createElement('report_name', 'Переходы со страниц ' . $serverName);
        $root->appendChild($name);

        $data = $this->GetLinksData($date1, $date2, $server, $limit_start, $limit_count);
        $reportData = $xml->createElement('report_data');
        $root->appendChild($reportData);

        foreach($data as $row)
        {
            $url = $row['scheme'] . '://' . $row['servStr'] . $row['pathStr'];
            if ($server)
                $urlHuman = $row['pathStr'];
            else
                $urlHuman = $url;
            if ($row['queryStr'] != '') {
                $url .= '?' . $row['queryStr'];
                $urlHuman .= '?' . $row['queryStr'];
            }
            if (strlen($urlHuman) > 50)
                $urlHuman = substr($urlHuman, 0, 47) . '...';
                
            $dataRow = $xml->createElement('row');
            $reportData->appendChild($dataRow);
            $dataRow->setAttribute('url', $url);
            $dataRow->setAttribute('urlHuman', $urlHuman);
            $dataRow->setAttribute('scheme', $row['scheme']);
            $dataRow->setAttribute('serverId', $row['serv']);
            $dataRow->setAttribute('serverStr', $row['servStr']);
            $dataRow->setAttribute('pathId', $row['path']);
            $dataRow->setAttribute('pathStr', $row['pathStr']);
            $dataRow->setAttribute('queryId', $row['query']);
            $dataRow->setAttribute('queryStr', $row['queryStr']);
            $dataRow->setAttribute('summ', $row['summ']);
        }

        if (count($data) == $limit_count)
        {
            $dataMore = $xml->createElement('report_data_more');
            $dataMore->setAttribute('start', $limit_count);
            $dataMore->setAttribute('count', $limit_count);
            if ($server)
                $dataMore->setAttribute('server', $server);
            $root->appendChild($dataMore);
        }

        $xsl = dirname(__FILE__) . '/templates/links.xsl';
        $pi = $xml->createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="'.$xsl.'"');
        $xml->insertBefore($pi, $root);
        return true;
    }
}


class LoggerModuleSourcesLinksMoreReport extends LoggerModuleSourcesLinksReportBaseClass implements LoggerReportInterface
{
    public function __construct(LoggerDatabase $database) 
    {
        parent::__construct($database);
    }

    public function GetReport($root, $date1, $date2, $params = false)
    {
        if (!is_array($params) || !isset($params['start']))
            return false;

        $limit_start = intval($params['start']);
        $limit_count = 100;

        if (isset($params['count']))
            $limit_count = intval($params['count']);

        $server = false;
        if (isset($params['server']) && $params['server'])
        {
            $server = intval($params['server']);
        }

        $xml = $root->ownerDocument;

        $data = $this->GetLinksData($date1, $date2, $server, $limit_start, $limit_count);
        $reportData = $xml->createElement('report_data');
        $root->appendChild($reportData);

        foreach($data as $row)
        {
            $url = $row['scheme'] . '://' . $row['servStr'] . $row['pathStr'];
            if ($server)
                $urlHuman = $row['pathStr'];
            else
                $urlHuman = $url;
            if ($row['queryStr'] != '') {
                $url .= '?' . $row['queryStr'];
                $urlHuman .= '?' . $row['queryStr'];
            }
            if (strlen($urlHuman) > 50)
                $urlHuman = substr($urlHuman, 0, 47) . '...';
                
            $dataRow = $xml->createElement('row');
            $reportData->appendChild($dataRow);
            $dataRow->setAttribute('url', $url);
            $dataRow->setAttribute('urlHuman', $urlHuman);
            $dataRow->setAttribute('scheme', $row['scheme']);
            $dataRow->setAttribute('serverId', $row['serv']);
            $dataRow->setAttribute('serverStr', $row['servStr']);
            $dataRow->setAttribute('pathId', $row['path']);
            $dataRow->setAttribute('pathStr', $row['pathStr']);
            $dataRow->setAttribute('queryId', $row['query']);
            $dataRow->setAttribute('queryStr', $row['queryStr']);
            $dataRow->setAttribute('summ', $row['summ']);
        }

        $xsl = dirname(__FILE__) . '/templates/links_more.xsl';
        $pi = $xml->createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="'.$xsl.'"');
        $xml->insertBefore($pi, $root);
        return true;
    }
}